﻿using System.Text.RegularExpressions;

namespace EventBusNet6;

public class VideoCommandService : IVideoCommandService
{
    private string OutPutDir = string.Empty;
    private string ProbePath = string.Empty;
    private string ExePath = string.Empty;
    private string NoticeUrl = string.Empty;
    public VideoCommandService(IOptions<FFmpegOptions> ffmpegOptions)
    {
        string basePath= AppContext.BaseDirectory;
        ExePath =Path.Combine(basePath, ffmpegOptions.Value.ExePath ?? "");
        ProbePath = Path.Combine(basePath, ffmpegOptions.Value.ProbePath ?? "");
        NoticeUrl = ffmpegOptions.Value.NoticeUrl ?? "";
        OutPutDir = ffmpegOptions.Value.OutPutDir ?? "";

        var path = "{yyyy}{MM}\\{dd}";
        if (string.IsNullOrWhiteSpace(OutPutDir))
        {
            var reg = new Regex(@"(\{.+?})");
            var match = reg.Matches(path);
            match.ToList().ForEach(a =>
            {
                var str = DateTime.Now.ToString(a.ToString().Substring(1, a.Length - 2)); // 每天一个目录
                path = path.Replace(a.ToString(), str);
            });
            OutPutDir = Path.Combine(basePath, path);
        }
    }
   
    public string CaptureVideoPicture(string inputPath, int width, int height, string guid)
    {
        /*********************************************
           * -t 表示共要多少时间。
           * *********************************************/
        StringBuilder stringBuilder = new StringBuilder();
        string outputPath = Path.Combine(OutPutDir, guid);
        if (!Directory.Exists(outputPath))
        {
            Directory.CreateDirectory(outputPath);
        }
        //ffmpeg -i test.asf -y -f image2 -t 0.001 -s 352x240 a.jpeg
        stringBuilder.Append($" -i \"{inputPath}\"  -y -f image2 -t 0.001 -s {width}x{height} {outputPath}\\capture.jpeg ");
        var cmd = new ExecuteCommand(stringBuilder.ToString(), outputPath, ExePath, NoticeUrl, guid);
        CommandService.GetInstance().Add(cmd);
        return outputPath;
    }

    public VideoInfoOutput VideoInfo(string inputPath,string guid)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append($"-select_streams v -show_entries format=duration,size,bit_rate,filename  -show_streams -v quiet  -of json -i  {inputPath}");
        var cmd = new ExecuteCommand(stringBuilder.ToString(), string.Empty , ProbePath, NoticeUrl, string.Empty);
        VideoInfoOutput? output = new VideoInfoOutput();
        output.Guid = guid;
        Func<IExecuteCommand, bool> canExcute = (cmd) =>
        {
            return true;
        };

        Action<IExecuteCommand> onCompleted = async (cmd) =>
        {
            //执行完成，需要处理其他事情
            JObject jsondat = JObject.Parse(cmd.OutData.ToString());
            JObject formatobj = JObject.Parse(jsondat["format"]?.ToString() ?? "");
            output.Duration = formatobj["duration"]?.ToString() ?? "";
            output.FileName = formatobj["filename"]?.ToString() ?? "";
            output.SizeByte = formatobj["size"]?.ToString() ?? "";
            output.BitRate = formatobj["bit_rate"]?.ToString() ?? "";

            JArray streamsarry = JArray.Parse(jsondat["streams"]?.ToString() ?? "");
            JObject streamobj = JObject.Parse(streamsarry[0]?.ToString() ?? "");

            output.Width = streamobj["width"]?.ToString() ?? "";
            output.Height = streamobj["height"]?.ToString() ?? "";
            output.CodeName = streamobj["codec_name"]?.ToString() ?? "";
            if (!string.IsNullOrWhiteSpace(cmd.NoticeUrl))
            {
                await NoticeUrl.PostJsonAsync(output);
            }
        };
        CommandService.GetInstance().RunExePath(cmd, canExcute, onCompleted);
        return output;
    }
    public AudioInfoOutput AudioInfo(string inputPath, string guid)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append($"-select_streams v -show_entries format=duration,size,bit_rate,filename  -v quiet  -of json -i  {inputPath}");
        var cmd = new ExecuteCommand(stringBuilder.ToString(), string.Empty, ProbePath, NoticeUrl, string.Empty);
        Func<IExecuteCommand, bool> canExcute = (cmd) =>
        {
            return true;
        };
        AudioInfoOutput? output = new AudioInfoOutput();
        output.Guid = guid;
        Action<IExecuteCommand> onCompleted = async (cmd) =>
        {
            //执行完成，需要处理其他事情
            JObject jsondat = JObject.Parse(cmd.OutData.ToString());
            JObject formatobj = JObject.Parse(jsondat["format"]?.ToString() ?? "");
            output.Duration = formatobj["duration"]?.ToString()??"";
            output.FileName = formatobj["filename"]?.ToString() ?? "";
            output.SizeByte = formatobj["size"]?.ToString() ?? "";
            output.BitRate = formatobj["bit_rate"]?.ToString() ?? "";
            if (!string.IsNullOrWhiteSpace(cmd.NoticeUrl))
            {
                await NoticeUrl.PostJsonAsync(output);
            }
        };
        CommandService.GetInstance().RunExePath(cmd, canExcute, onCompleted);
        return output;
    }
}
